//
//  ViewController.swift
//  RHello
//
//  Created by 吴智民 on 2020/5/17.
//  Copyright © 2020 Lanchc. All rights reserved.
//

import UIKit
import WebKit
import CocoaAsyncSocket

class ViewController: UIViewController {
    /**IP地址*/
//    @IBOutlet weak var hostip: UITextField!
//    /**端口*/
//    @IBOutlet weak var ported: UITextField!
    /**日志*/
    @IBOutlet weak var logger: UITextView!
    /**监控*/
    @IBOutlet weak var wbView: WKWebView!
    /**上下*/
    @IBOutlet weak var buttonU: UIButton!
    @IBOutlet weak var buttonD: UIButton!
    /**左右*/
    @IBOutlet weak var buttonL: UIButton!
    @IBOutlet weak var buttonR: UIButton!
    /**停止*/
    @IBOutlet weak var buttonS: UIButton!
    
    
    @IBOutlet weak var rbuttonS: UIButton!
    
    @IBOutlet weak var rbuttonU: UIButton!
    
    @IBOutlet weak var rbuttonD: UIButton!
    //    /**连接实例*/
    @IBOutlet weak var rbuttonL: UIButton!
    
    
    @IBOutlet weak var rbuttonR: UIButton!
    //    lazy var clientSocket: GCDAsyncSocket = {
//        let c = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.main)
//        return c
//    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        SkManager.default.tx = logger
        SkManager.default.wb = wbView
        
    }
    
    
    @IBAction func onTapperLink(_ sender: UIBarButtonItem) {
        print("链接操作")
        SkManager.default.wb = wbView
        SkManager.default.loadURL()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        title = "控制"
        
    
        /// 绑定事件
        buttonU.addTarget(self, action: #selector(onTapUp), for: .touchDown)
        buttonU.addTarget(self, action: #selector(onTapStop), for: .touchUpInside)
        /// 绑定事件
        buttonD.addTarget(self, action: #selector(onTapDown), for: .touchDown)
        buttonD.addTarget(self, action: #selector(onTapStop), for: .touchUpInside)
        /// 绑定事件
        buttonL.addTarget(self, action: #selector(onTapLeft), for: .touchDown)
        buttonL.addTarget(self, action: #selector(onTapStop), for: .touchUpInside)
        /// 绑定事件
        buttonR.addTarget(self, action: #selector(onTapRight), for: .touchDown)
        buttonR.addTarget(self, action: #selector(onTapStop), for: .touchUpInside)
        /// 绑定事件
        buttonS.addTarget(self, action: #selector(onTapStop), for: .touchUpInside)
        rbuttonS.addTarget(self, action: #selector(onTapStop), for: .touchUpInside)
        
        
        rbuttonU.addTarget(self, action: #selector(rTapperUp), for: .touchUpInside)
        rbuttonD.addTarget(self, action: #selector(rTapperDw), for: .touchUpInside)
        rbuttonL.addTarget(self, action: #selector(rTapperLe), for: .touchUpInside)
        rbuttonR.addTarget(self, action: #selector(rTapperRi), for: .touchUpInside)
        
    }
    
    
    /**是否锁*/
    var isTapLook = false
    /**是否按住*/
    var isNexTap: Bool = false
    
    /** =========================== 上 =========================== */
  
    @objc private func onTapUp() {
        isNexTap = true
        print("按下")
        onTap(index: 1000)
        guard !isTapLook else { return }
        
        isTapLook = true
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) { [weak self] in
            guard let wkThis = self else { return }
            wkThis.isTapLook = false
            if wkThis.isNexTap {
                wkThis.onTapUp()
            }
        }
    }
    
    /** =========================== 下 =========================== */
    @objc private func onTapDown() {
        isNexTap = true
        print("按上")
        onTap(index: 1001)
        guard !isTapLook else { return }
        
        isTapLook = true
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) { [weak self] in
            guard let wkThis = self else { return }
            wkThis.isTapLook = false
            if wkThis.isNexTap {
                wkThis.onTapDown()
            }
        }
    }
    /** =========================== 左 =========================== */
    @objc private func onTapLeft() {
        isNexTap = true
        print("按左")
        onTap(index: 1002)
        guard !isTapLook else { return }
        
        isTapLook = true
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) { [weak self] in
            guard let wkThis = self else { return }
            wkThis.isTapLook = false
            if wkThis.isNexTap {
                wkThis.onTapLeft()
            }
        }
    }
    
    /** =========================== 右 =========================== */
    @objc private func onTapRight() {
        isNexTap = true
        print("按右")
        onTap(index: 1003)
        guard !isTapLook else { return }

        isTapLook = true
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) { [weak self] in
            guard let wkThis = self else { return }
            wkThis.isTapLook = false
            if wkThis.isNexTap {
                wkThis.onTapRight()
            }
        }
    }
    
    /** =========================== 右 =========================== */
    
    @objc private func onTapStop() {
        print("松开")
        onTap(index: 1004)
        isTapLook = false
        isNexTap = false
    }
    
    private func onTap(index: Int) {
        
        self.view.endEditing(true)
        
        switch index {
        case 1000:
            SkManager.default.sendMessage(bc: "ONA")
            break
        case 1001:
            SkManager.default.sendMessage(bc: "ONB")
            break
            
        case 1002:
            SkManager.default.sendMessage(bc: "ONC")
            break
            
        case 1003:
            SkManager.default.sendMessage(bc: "OND")
            break
            
        case 1004:
            SkManager.default.sendMessage(bc: "ONF")
            break
            
        case 2001:
            SkManager.default.sendMessage(bc: "ONL")
            break
        case 2002:
            SkManager.default.sendMessage(bc: "ONI")
            break
        case 2003:
            SkManager.default.sendMessage(bc: "ONK")
            break
        case 2004:
            SkManager.default.sendMessage(bc: "ONJ")
            break
            
        default:
            break
        }
    }
    
    @objc func rTapperUp() {
        print("\(#function)")
        isNexTap = true
        print("按上")
        onTap(index: 2003)
//        guard !isTapLook else { return }
//
//        isTapLook = true
//
//        print("按上x")
//
//        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) { [weak self] in
//            guard let wkThis = self else { return }
//            wkThis.isTapLook = false
//            if wkThis.isNexTap {
//                wkThis.rTapperUp()
//            }
//        }
    }
    
    @objc func rTapperDw() {
        print("\(#function)")
        isNexTap = true
        print("按下")
        onTap(index: 2004)
//        guard !isTapLook else { return }
//
//        isTapLook = true
//
//        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) { [weak self] in
//            guard let wkThis = self else { return }
//            wkThis.isTapLook = false
//            if wkThis.isNexTap {
//                wkThis.rTapperDw()
//            }
//        }
    }
    
    @objc func rTapperLe() {
        print("\(#function)")
        isNexTap = true
        print("按左")
        onTap(index: 2001)
//        guard !isTapLook else { return }
//
//        isTapLook = true
//
//        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) { [weak self] in
//            guard let wkThis = self else { return }
//            wkThis.isTapLook = false
//            if wkThis.isNexTap {
//                wkThis.rTapperLe()
//            }
//        }
    }
    
    @objc func rTapperRi() {
        print("\(#function)")
        isNexTap = true
        print("按右")
        onTap(index: 2002)
//        guard !isTapLook else { return }
//
//        isTapLook = true
//
//        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) { [weak self] in
//            guard let wkThis = self else { return }
//            wkThis.isTapLook = false
//            if wkThis.isNexTap {
//                wkThis.rTapperRi()
//            }
//        }
    }
    
//    /// 连接
//    @IBAction func connectTap(_ sender: UIButton) {
//        self.view.endEditing(true)
//        
//        SkManager.default.clientSocket.disconnect()
//        
//        loadURL()
//        
//        do {
//            guard SkManager.default.hsip.isEmpty else {
//                SkManager.default.showMessage("请输入连接地址")
//                return
//            }
//            
//            guard SkManager.default.prot.isEmpty else {
//                SkManager.default.showMessage("请输入连接端口")
//                return
//            }
//            
//            try SkManager.default.clientSocket.connect(toHost: SkManager.default.hsip, onPort: UInt16(SkManager.default.prot)!, withTimeout: -1)
//            
//        } catch {
//            SkManager.default.showMessage("链接失败")
//        }
//    }
//    
//    
//    /// 断开
//    @IBAction func disconnectTap(_ sender: UIButton) {
//        
//        self.view.endEditing(true)
//        
//        SkManager.default.clientSocket.disconnect()
//        SkManager.default.showMessage("断开链接")
//    }
    
 
}

//extension ViewController: GCDAsyncSocketDelegate {
//
//
//    /// 链接成功
//    func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) {
//
//
//        showMessage("链接成功！")
//
//        let address = "Server IP：" + "\(host)"
//
//        showMessage(address)
//
//        clientSocket.readData(withTimeout: -1, tag: 0)
//    }
//
//    /// 接受消息
//    func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
//
//        let text = String(data: data, encoding: .utf8)
//
//        showMessage(text!)
//
//        clientSocket.readData(withTimeout: -1, tag: 0)
//    }
//    /// 断开链接
//    func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
//
//        showMessage("断开链接")
//    }
//
//    private func sendMessage(bc: String) {
//        // tag: message tag
//        clientSocket.write( bc.data(using: .utf8), withTimeout: -1, tag: 0)
//    }
//
//    // 现实消息
//    private func showMessage(_ str: String) {
//        logger.text = logger.text.appendingFormat("%@\n", str)
//    }
//}
